package ua.kharkov.photo.dal;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;

import ua.kharkov.photo.bl.ImageThumbnailCreator;
import ua.kharkov.photo.model.Image;
import ua.kharkov.photo.model.User;

public class JDBCImagesRepository extends AbstractRepository implements
		ImageRepository {

	private static final String INSERT_IMAGE_QUERY = "INSERT INTO images "
			+ "(id, user_id, data, thumbnail_data) VALUES (:id, :user_id, :data, :thumbnail_data)";
	private static final String GET_IMAGES_BY_USER_ID = "SELECT * FROM images WHERE user_id = :userid";

	@Override
	public void insertImage(Image image) throws IOException {

		ByteArrayInputStream inputStreamLarge = new ByteArrayInputStream(
				image.getData());
		ByteArrayInputStream inputStreamThumbnail = ImageThumbnailCreator
				.getInputThumbnailStream(inputStreamLarge);

		inputStreamLarge = new ByteArrayInputStream(image.getData());

		Map<String, Object> parameters = new HashMap<String, Object>();

		parameters.put("id", 0);
		parameters.put("user_id", image.getUserId());
		parameters.put("data", inputStreamLarge);
		parameters.put("thumbnail_data", inputStreamThumbnail);

		namedParameterJdbcTemplate.update(INSERT_IMAGE_QUERY, parameters);

	}

	@Override
	public List<Image> getImagesbyUser(User user) {
		SqlParameterSource paramSourse = new MapSqlParameterSource("userid",
				user.getId());

		List<Image> images = namedParameterJdbcTemplate.query(
				GET_IMAGES_BY_USER_ID, paramSourse,
				ParameterizedBeanPropertyRowMapper.newInstance(Image.class));

		for (Image image : images) {
			image.setPath("getImage/" + Integer.toString(image.getId()));
			image.setThumnailPath(image.getPath() + "th");
		}

		return images;
	}
}
